package com.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BasePageRes;
import com.base.BaseServiceImpl;
import com.entity.ArticalComment;
import com.exception.ServiceException;
import com.repository.ArticalCommentRepository;
import com.req.ArticalCommentPageReq;
import com.req.ArticalCommentReq;
import com.res.ArticalCommentRes;
import com.res.UserRes;
import com.service.ArticalCommentService;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArticalCommentServiceImpl extends BaseServiceImpl<ArticalCommentReq,ArticalCommentRes, ArticalCommentRepository, ArticalComment> implements ArticalCommentService {
    @Autowired
    private ArticalCommentRepository articalCommentRepository;

    @Override
    public ArticalCommentRes saveComment(ArticalCommentReq req) {
        return this.handle(req);
    }

    @Override
    public BasePageRes queryPage(ArticalCommentPageReq pageReq, UserRes user) {
        if (StringUtils.isEmpty(pageReq.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(pageReq.getSize())) {
            throw new ServiceException("请传入size");
        }
        if(!StringUtil.isEmpty(pageReq.getDes())){
            pageReq.setDes("%"+pageReq.getDes()+"%");
        }
        //一级回复集合

        Page<ArticalCommentRes> pages = new Page<>(pageReq.getPage(), pageReq.getSize());
        IPage<ArticalCommentRes> articalIPage = articalCommentRepository.searchFirst(pages,pageReq);
        BasePageRes<ArticalCommentRes> pageRes = this.convertIpage(articalIPage,  new ArticalCommentRes());
        List<ArticalCommentRes> firstList = pageRes.getList();
        //二级回复集合
        List<ArticalCommentRes> secendList = articalCommentRepository.searchSecend(pageReq);
        for (ArticalCommentRes articalOne : firstList) {
            if(articalOne == null){
                continue;
            }
            List<ArticalCommentRes> collectTwo = secendList.stream().filter(item -> {
                return Objects.equals(item.getReplyId(), articalOne.getId());
            }).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(collectTwo)){
                continue;
            }
            articalOne.setResList(collectTwo);

        }
        return pageRes;

    }

}
